<script setup>
import { ref } from 'vue'
import { GetSpeciesService, AddSpeciesService, DelSpeciesService } from '@/api/species'
import DeleteButton from './components/DeleteButton.vue';
import AddButton from './components/AddButton.vue';
const speciesList = ref([])
const loading = ref(true)
const dialogVisible = ref(false)

const formModel = ref({
  name: ''
})
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    {
      pattern: /^\S{1,10}$/,
      message: '分类名必须是1-10位的非空字符',
      trigger: 'blur'
    }
  ]
}

//获取种类
const getSpeciesList = async () => {
  loading.value = true
  const res = await GetSpeciesService()
  speciesList.value = res.data.data
  loading.value = false
  console.log(res)
}
getSpeciesList()

//添加种类
const onSubmit = async () => {
  const res = await AddSpeciesService(formModel.value)
  console.log(res)
  formModel.value = ''
  getSpeciesList()
  ElMessage.success('添加成功')
  dialogVisible.value = false
}
//删除种类
const onDelChannel = async (row) => {
  await ElMessageBox.confirm('你确认删除该白蚁种类吗？', '温馨提示', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  })
  const res = await DelSpeciesService(row.id)

  console.log(res.data.code)
  if (res) {
    if (res.data.code == 1) ElMessage.success('删除成功')
    else ElMessage.error(res.data.msg)
  } else ElMessage.error('服务异常')
  getSpeciesList()
}
</script>
<template>
  <page-container title="白蚁种类">
    <!-- 添加种类弹窗 -->
    <el-dialog v-model="dialogVisible" title="添加种类" width="30%">
      <el-form
        ref="formRef"
        :model="formModel"
        :rules="rules"
        label-width="100px"
        style="padding-right: 30px"
      >
        <el-form-item label="种类名称" prop="name">
          <el-input v-model="formModel.name" @keyup.enter="onSubmit"></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button @click="onSubmit" type="primary"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 表格头部 -->
    <template #extra>
      <!-- <el-button type="primary" @click="dialogVisible = true">添加种类</el-button> -->
      <add-button @click="dialogVisible = true"></add-button>
    </template>
    <!-- 表格主体 -->
    <el-table v-loading="loading" :data="speciesList" style="width: 100%">
      <el-table-column label="序号" width="100" type="index"></el-table-column>
      <el-table-column label="白蚁名称" prop="name"></el-table-column>
      <!-- 操作部分 -->
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <delete-button @click="onDelChannel(row)"></delete-button>
        </template>
      </el-table-column>

      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
  </page-container>
</template>
